<?php
//=======================================
//###################################
// Kayako Web Solutions
//
// Source Copyright 2001-2004 Kayako Web Solutions
// Unauthorized reproduction is not allowed
// License Number: $%LICENSE%$
// $Author: vshoor $ ($Date: 2006/04/11 20:58:15 $)
// $RCSfile: staff_questions.php,v $ : $Revision: 1.12 $ 
//~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
//
//###################################
//=======================================


if (!defined("INSWIFT")) {
	trigger_error("Unable to process $PHP_SELF", E_USER_ERROR);
}

if ($_SWIFT["staff"]["kb_entab"] == "0")
{
	echo '<font face="Verdana, Arial, Helvetica" size="2" color="red"><b>'.$_SWIFT["language"]["nopermission"].'</b></font>';
	exit;
}

require_once ("./modules/knowledgebase/functions_knowledgebase.php");
require_once ("./includes/functions_html.php");
require_once ("./includes/functions_users.php");
require_once ("./includes/functions_jscache.php");
require_once ("./includes/data_mimelist.php");
$template->loadLanguageSection("knowledgebase");

$interface->assignQuickLink($_SWIFT["language"]["managecategories"], "index.php?_m=knowledgebase&_a=managecategories", "icon_list.gif");
$interface->assignQuickLink($_SWIFT["language"]["managequestions"], "index.php?_m=knowledgebase&_a=managequestions", "icon_topicyellow.gif");
$interface->assignQuickLink($_SWIFT["language"]["insertcategory"], "index.php?_m=knowledgebase&_a=insertcategory", "icon_newcategory.gif");
$interface->assignQuickLink($_SWIFT["language"]["insertquestion"], "index.php?_m=knowledgebase&_a=insertquestion", "icon_inserttopic.gif");

renderCategoryList();

/**
* ###############################################
* FUNCTION DECLARATIONS
* ###############################################
*/

/**
* Callback for parsing KB Article data
*/
function _articleFields($arg)
{
	global $_SWIFT, $_sladays;
	$record = &$arg[0];
	$fields = &$arg[1];

	$record["kbarticles.subject"] = htmlspecialchars($record["subject"]);
	$record["kbarticles.dateline"] = edate($_SWIFT["settings"]["dt_datetimeformat"], $record["articledateline"]);
	
	if ($record["articlestatus"] == ARTICLE_PUBLISHED)
	{
		$articlestatus = $_SWIFT["language"]["published"];
		$statusicon = "icon_topicyellow.gif";
	} else if ($record["articlestatus"] == ARTICLE_PRIVATE) {
		$articlestatus = $_SWIFT["language"]["private"];
		$statusicon = "icon_topicprivate.gif";
	} else if ($record["articlestatus"] == ARTICLE_DRAFT) {
		$articlestatus = $_SWIFT["language"]["draft"];
		$statusicon = "icon_topicdraft.gif";
	}
	$record["kbarticles.articlestatus"] = $articlestatus;

	$record["kbarticles.views"] = $record["views"];
	
	$record["kbarticles.subject"] = '<table width="100%"  border="0" cellspacing="0" cellpadding="1"><tr><td width="1"><img src="'. $_SWIFT["themepath"] .$statusicon.'" border="0" /></td>'. iif($record["hasattachments"]==1, '<td width="1"><img src="'. $_SWIFT["themepath"] .'icon_paperclip.gif" border="0" /></td>').iif($record["totalcomments"]>0, '<td width="1"><img src="'. $_SWIFT["themepath"] .'icon_comment.gif" border="0" /></td>') .'<td><span class="smalltext">&nbsp;<a href="index.php?_m=knowledgebase&_a=editquestion&kbarticleid='. $record["kbarticleid"] .'">'. $record["subject"] .'</a></span></td></tr></table>';

	$record["kbarticles.articlerating"] = '<img src="'. $_SWIFT["themepath"] . getRatingImage($record["articlerating"]) .'" border="0" />&nbsp;';

	$record["options"] = '<a href="index.php?_m=knowledgebase&_a=editquestion&kbarticleid='. $record["kbarticleid"] .'" title="'. $_SWIFT["language"]["edit"] .'"><img src="'. $_SWIFT["themepath"] .'icon_edit.gif" border="0">&nbsp;'. $_SWIFT["language"]["edit"] .'</a>&nbsp;&nbsp;&nbsp;&nbsp;<a onClick="javascript:doConfirm(\''. $_SWIFT["language"]["kbarticledelconfirmmsg"] .'\', \'index.php?_m=knowledgebase&_a=managequestions&do=delete&kbarticleid='. $record["kbarticleid"] .'\');" href="#" title="'. $_SWIFT["language"]["delete"] .'"><img src="'. $_SWIFT["themepath"] .'icon_delete.gif" border="0">&nbsp;'. $_SWIFT["language"]["delete"] .'</a>&nbsp;';

	return $record;
}

/**
* Mass Action: Delete KB Articles
*/
function _maDeleteKBArticles()
{
	global $dbCore, $_SWIFT, $infomessage;

	if (_is_array($_POST["itemid"]))
	{
		$infomessage = $_SWIFT["language"]["dlarticlesdelconfirm"];
		deleteKBArticles($_POST["itemid"]);
	}
}



/**
* ###############################################
* MANAGE QUESTIONS
* ###############################################
*/
if ($eventaction == "managequestions")
{
	if ($_GET["do"] == "delete" && !empty($_GET["kbarticleid"]))
	{
		$infomessage = $_SWIFT["language"]["dlarticledelconfirm"];

		deleteKBArticles(array($_GET["kbarticleid"]));
	}

	if (!empty($_REQUEST["insertarticle"]))
	{
		$infomessage = sprintf($_SWIFT["language"]["kbarticleinsertconfirm"], htmlspecialchars($_REQUEST["insertarticle"]));
	} else if (!empty($_REQUEST["updatearticle"])) {
		$infomessage = sprintf($_SWIFT["language"]["kbarticleupdateconfirm"], htmlspecialchars($_REQUEST["updatearticle"]));
	} else if (!empty($_REQUEST["importconfirm"])) {
		$infomessage = $_SWIFT["language"]["importconfirm"];
	}
	
	$options["recordsperpage"] = "10";
	$options["sortby"] = "kbarticles.dateline";
	$options["sortorder"] = "desc";
	$options["appendurl"] = "&filter=".intval($_REQUEST["filter"])."&filterkbcategoryid=".intval($_REQUEST["filterkbcategoryid"]);
	$options["massaction"][0]["title"] = $_SWIFT["language"]["delete"];
	$options["massaction"][0]["callback"] = "_maDeleteKBArticles";

	$options["idname"] = "kbarticleid";
	$options["quicksearch"] = true;

	$options["advancedsearch"][0]["title"] = $_SWIFT["language"]["kbsubject"];
	$options["advancedsearch"][0]["query"] = 'SELECT *, kbarticles.dateline AS articledateline FROM `'. TABLE_PREFIX .'kbarticles` AS kbarticles LEFT JOIN `'. TABLE_PREFIX .'kbarticledata` AS kbarticledata ON (kbarticles.kbarticleid = kbarticledata.kbarticleid) WHERE kbarticles.subject LIKE \'%$_searchstr%\' $_sortjoin;';

	$options["advancedsearch"][1]["title"] = $_SWIFT["language"]["kbcontents"];
	$options["advancedsearch"][1]["query"] = 'SELECT *, kbarticles.dateline AS articledateline FROM `'. TABLE_PREFIX .'kbarticles` AS kbarticles LEFT JOIN `'. TABLE_PREFIX .'kbarticledata` AS kbarticledata ON (kbarticles.kbarticleid = kbarticledata.kbarticleid) WHERE kbarticledata.contents LIKE \'%$_searchstr%\' $_sortjoin;';

	$options["callback"] = "_articleFields";

	$options["toolbar"][0]["title"] = $_SWIFT["language"]["filter"];
	$options["toolbar"][0]["url"] = "javascript:switchDisplay('filtercat');";

	$fields[0]["name"] = "kbarticles.subject";
	$fields[0]["title"] = $_SWIFT["language"]["kbsubject"];
	$fields[0]["width"] = "";

	$fields[1]["name"] = "kbarticles.dateline";
	$fields[1]["title"] = $_SWIFT["language"]["kbdate"];
	$fields[1]["width"] = "150";
	$fields[1]["align"] = "center";

	$fields[2]["name"] = "kbarticles.articlestatus";
	$fields[2]["title"] = $_SWIFT["language"]["kbarticlestatus"];
	$fields[2]["width"] = "130";
	$fields[2]["align"] = "center";

	$fields[3]["name"] = "kbarticles.articlerating";
	$fields[3]["title"] = $_SWIFT["language"]["kbrating"];
	$fields[3]["width"] = "120";
	$fields[3]["align"] = "center";

	$fields[4]["name"] = "kbarticles.views";
	$fields[4]["title"] = $_SWIFT["language"]["kbviews"];
	$fields[4]["width"] = "80";
	$fields[4]["align"] = "center";

/*	$fields[5]["type"] = "custom";
	$fields[5]["name"] = "options";
	$fields[5]["title"] = $_SWIFT["language"]["options"];
	$fields[5]["width"] = "150";
	$fields[5]["align"] = "center";*/

	$grid = new Grid();

	$interface->staffHeader($_SWIFT["language"]["knowledgebase"]." &gt; ".$_SWIFT["language"]["managequestions"], 4);

	$interface->staffNavBar('<a href="index.php?_m=knowledgebase&_a=managecategories" title="'.$_SWIFT["language"]["categories"].'">'.$_SWIFT["language"]["categories"].'</a> &raquo; <a href="index.php?_m=knowledgebase&_a=managequestions" title="'.$_SWIFT["language"]["managequestions"].'">'.$_SWIFT["language"]["managequestions"].'</a>', "", 4);

	unset($filtersql);
	if (!empty($_REQUEST["filterkbcategoryid"]))
	{
		// Get all articles under given filter category
		$filterkbarticleidlist = $filterkbcatlist = array();
		$filterkbcatlist[] = $_REQUEST["filterkbcategoryid"];
		$filterkbcatlist = array_merge($filterkbcatlist, fetchChildCategories($_REQUEST["filterkbcategoryid"], ($_temp = array())));

		$dbCore->query("SELECT `kbarticleid` FROM `". TABLE_PREFIX ."kbarticlelinks` WHERE `kbcategoryid` IN(". buildIN($filterkbcatlist) .");");
		while ($dbCore->nextRecord())
		{
			if (!in_array($dbCore->Record["kbarticleid"], $filterkbarticleidlist))
			{
				$filterkbarticleidlist[] = $dbCore->Record["kbarticleid"];
			}
		}
		$filtersql = " WHERE kbarticles.kbarticleid IN(". buildIN($filterkbarticleidlist) .")";
	}

	$grid->start("kbarticles", $_SWIFT["language"]["articlelist"], 'SELECT *, kbarticles.dateline AS articledateline FROM `'. TABLE_PREFIX .'kbarticles` AS kbarticles'. $filtersql .' $_sortjoin;', 'SELECT COUNT(*) AS totalitems FROM `'. TABLE_PREFIX .'kbarticles` AS kbarticles'. $filtersql .';', 'SELECT *, kbarticles.dateline AS articledateline FROM `'. TABLE_PREFIX .'kbarticles` AS kbarticles LEFT JOIN `'. TABLE_PREFIX .'kbarticledata` AS kbarticledata ON (kbarticles.kbarticleid = kbarticledata.kbarticleid) WHERE kbarticles.subject LIKE \'%$_searchstr%\' OR kbarticledata.contents LIKE \'%$_searchstr%\' $_sortjoin;', $fields, $options);

	printInfoBox($infomessage);
	printErrorBox($errormessage);

	// ======= FILTER =======
	echo '<div id="filtercat" style="DISPLAY:none;">'.SWIFT_CRLF;
	printFormStart();
	printMainTableHeader($_SWIFT["language"]["filter"]);

	$options = buildKBCategorySelectData(0);

	printSelectRow("filterkbcategoryid", $_SWIFT["language"]["kbfiltercat"], $_SWIFT["language"]["desc_kbfiltercat"], $options);
	printSubmitRow($_SWIFT["language"]["filter"]);
	printMainTableFooter();
	addHiddenField("_m", "knowledgebase");
	addHiddenField("_a", "managequestions");
	addHiddenField("filter", "1");
	printFormEnd();
	echo '<BR /></div>'.SWIFT_CRLF;	

	$grid->display("kbarticles");

	echo '<BR /><span class="smalltext">'. $_SWIFT["language"]["legend"] .' <img src="'. $_SWIFT["themepath"] .'icon_topicyellow.gif" border="0" /> '. $_SWIFT["language"]["published"].'&nbsp;&nbsp;&nbsp; <img src="'. $_SWIFT["themepath"] .'icon_topicprivate.gif" border="0" /> '. $_SWIFT["language"]["private"].'&nbsp;&nbsp;&nbsp; <img src="'. $_SWIFT["themepath"] .'icon_topicdraft.gif" border="0" /> '. $_SWIFT["language"]["draft"].'<!--&nbsp;&nbsp;&nbsp; <img src="'. $_SWIFT["themepath"] .'icon_paperclip.gif" border="0" /> '. $_SWIFT["language"]["hasattachments"] .'-->&nbsp;&nbsp;&nbsp; <img src="'. $_SWIFT["themepath"] .'icon_comment.gif" border="0" /> '. $_SWIFT["language"]["hascomments"].'&nbsp;&nbsp;&nbsp;</span>';

	$interface->staffFooter();








/**
* ###############################################
* INSERT KB QUESTION
* ###############################################
*/
} else if ($eventaction == "insertquestion") {
	if ($_POST["step"] == 1)
	{
		if (trim($_POST["subject"]) == "" || trim($_POST["displayorder"]) == "")
		{
			$errormessage = $_SWIFT["language"]["requiredfieldempty"];
		} else if (!count($_POST["kbcategoryid"])) {
			$errormessage = $_SWIFT["language"]["selectlink"];			
		} else {
			$_POST["displayorder"] = iif(empty($_POST["displayorder"]), "1", $_POST["displayorder"]);	

			$kbarticleid = insertKBArticle($_POST["subject"], $_POST["articlestatus"], $_POST["displayorder"], $_POST["kbcategoryid"], $_POST["contents"]);

			if (!empty($_POST["ticketid"]))
			{
				// We need to redirect back to ticket listing.
				header("location: index.php?_m=tickets&_a=manage&departmentid=". intval($_POST["departmentid"]) ."&ticketstatusid=".intval($_POST["ticketstatusid"]));
				exit;
			}

			printRedirect(sprintf($_SWIFT["language"]["kbarticleinsertconfirm"], htmlspecialchars($_POST["subject"])), "index.php?_m=knowledgebase&_a=managequestions&insertarticle=".urlencode($_POST["subject"]));
			exit;
		}
	}

	if ($_SWIFT["settings"]["kb_staffwysiwyg"] == 1)
	{
		$template->assign("htmlarea", true);
	}

	$interface->staffHeader($_SWIFT["language"]["knowledgebase"]." &gt; ".$_SWIFT["language"]["insertquestion"], 4);

	$interface->staffNavBar('<a href="index.php?_m=knowledgebase&_a=managequestions" title="'.$_SWIFT["language"]["managequestions"].'">'.$_SWIFT["language"]["managequestions"].'</a> &raquo; '.'<a href="index.php?_m=knowledgebase&_a=insertquestion" title="'.$_SWIFT["language"]["insertquestion"].'">'.$_SWIFT["language"]["insertquestion"].'</a>', "", 4);

	printInfoBox($infomessage);
	printErrorBox($errormessage);

	renderKBQuestionForm(INSERT);
	
	$template->assign("backurl", "index.php?_m=knowledgebase&_a=managequestions");

	$interface->staffFooter();




/**
* ###############################################
* EDIT KB QUESTION
* ###############################################
*/
} else if ($eventaction == "editquestion") {
	$_kbarticle = $dbCore->queryFetch("SELECT * FROM `". TABLE_PREFIX ."kbarticles` AS kbarticles LEFT JOIN `". TABLE_PREFIX ."kbarticledata` AS kbarticledata ON (kbarticles.kbarticleid = kbarticledata.kbarticleid) WHERE kbarticles.kbarticleid = '". intval($_REQUEST["kbarticleid"]) ."';");
	if (empty($_kbarticle["kbarticleid"]))
	{
		trigger_error($_SWIFT["language"]["invalidkbarticle"], E_USER_ERROR);
	}

	if ($_GET["do"] == "exportpdf")
	{
		makeArticlePDF($_kbarticle["kbarticleid"], true);
		exit;
	}

	if ($_POST["step"] == 1)
	{
		if (trim($_POST["subject"]) == "" || trim($_POST["displayorder"]) == "")
		{
			$errormessage = $_SWIFT["language"]["requiredfieldempty"];
		} else if (!count($_POST["kbcategoryid"])) {
			$errormessage = $_SWIFT["language"]["selectlink"];
		} else {
			$_POST["displayorder"] = iif(empty($_POST["displayorder"]), "1", $_POST["displayorder"]);	

/*			$_rckbcategoryidlist = array();
			$dbCore->query("SELECT * FROM `". TABLE_PREFIX ."kbarticlelinks` WHERE `kbarticleid` = '". intval($_kbarticle["kbarticleid"]) ."';");
			while ($dbCore->nextRecord())
			{
				$_rckbcategoryidlist[] = $dbCore->Record["kbcategoryid"];
			}
*/
			$kbarticleid = updateKBArticle($_kbarticle["kbarticleid"], $_POST["subject"], $_POST["articlestatus"], $_POST["displayorder"], $_POST["kbcategoryid"], $_POST["contents"]);

			// Recount Bug Fix
//			recountKBCategory($_rckbcategoryidlist);

			printRedirect(sprintf($_SWIFT["language"]["kbarticleupdateconfirm"], htmlspecialchars($_POST["subject"])), "index.php?_m=knowledgebase&_a=managequestions&updatearticle=".urlencode($_POST["subject"]));
			exit;
		}
	}

	$_POST = array_merge($_POST, $_kbarticle);

	$template->assign("itemoptiontitle", $_SWIFT["language"]["articleoptions"]);
	$interface->assignItemOption($_SWIFT["language"]["exportpdf"], "index.php?_m=knowledgebase&_a=editquestion&do=exportpdf&kbarticleid=". $_kbarticle["kbarticleid"], "mimeico_pdf.gif");
	$interface->assignItemOption($_SWIFT["language"]["deletearticle"], "", "icon_delete.gif", "", "doConfirm('". $_SWIFT["language"]["kbarticledelconfirmmsg"] ."', 'index.php?_m=knowledgebase&_a=managequestions&do=delete&kbarticleid=". $_kbarticle["kbarticleid"] ."')");

	if ($_SWIFT["settings"]["kb_staffwysiwyg"] == 1)
	{
		$template->assign("htmlarea", true);
	}

	$interface->staffHeader($_SWIFT["language"]["knowledgebase"]." &gt; ".$_SWIFT["language"]["editquestion"], 4);

	$interface->staffNavBar('<a href="index.php?_m=knowledgebase&_a=managequestions" title="'.$_SWIFT["language"]["managequestions"].'">'.$_SWIFT["language"]["managequestions"].'</a> &raquo; '.'<a href="index.php?_m=knowledgebase&_a=editquestion&kbarticleid='. intval($_kbarticle["kbarticleid"]) .'" title="'.$_SWIFT["language"]["editquestion"].'">'.$_SWIFT["language"]["editquestion"].'</a>', "", 4);

	printInfoBox($infomessage);
	printErrorBox($errormessage);

	renderKBQuestionForm(EDIT);
	
	$template->assign("backurl", "index.php?_m=knowledgebase&_a=managequestions");

	$interface->staffFooter();
}


?>